package ReentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @功能
 * @创建时间 2019/12/20
 * 使用ReentrantLock还可以调用lockInterruptd方法做出响应
 * 在一个线程等待锁的过程中，可以被打断
 */
public class ReentrantLock4 {
    public static void main(String[] args) {

        Lock lock = new ReentrantLock();
        Thread t1 = new Thread(()->{
           try {
               lock.lock();
               System.out.println("t1 start");
               TimeUnit.SECONDS.sleep(Integer.MAX_VALUE); // 永久沉睡
           } catch (InterruptedException e) {
               e.printStackTrace();
           }finally {
               lock.unlock();
           }
        });
        t1.start();
        Thread t2 = new Thread(()->{

           try {
          //     lock.lock();
               lock.lockInterruptibly(); // 可以对Interruptibly方法做出响应
               System.out.println("t2 start");
               TimeUnit.SECONDS.sleep(5);
           } catch (InterruptedException e) {
               System.out.println("Interrupted!");
     //          e.printStackTrace();
           }finally {
               if(lock.tryLock()){
               lock.unlock();}
           }
        });
        t2.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt(); //打断线程t2的等待
    }
}
